package com.heima.leetcode.practice;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 111. 二叉树的最小深度
 * @date 2025/5/22 16:31
 */
public class E111 {

    /**
     * 方法一：递归
     *
     * @param root 根节点
     * @return 二叉树的最小深度
     */
    public int minDepth1(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) return 1;
        else if (root.left == null)
            return minDepth1(root.right) + 1;
        else if (root.right == null)
            return minDepth1(root.left) + 1;
        int lDepth = minDepth1(root.left);
        int rDepth = minDepth1(root.right);
        return Math.min(lDepth, rDepth) + 1;
    }

    /**
     * 方法二：用层序遍历
     *
     * @param root 根节点
     * @return 二叉树的最小深度
     */
    @SuppressWarnings("all")
    public int minDepth2(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int level = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode last = queue.poll();
                if (last.left == null && last.right == null)
                    return level;
                if (last.left != null)
                    queue.offer(last.left);
                if (last.right != null)
                    queue.offer(last.right);
            }
            level++;
        }
        return level;
    }
}
